package com.intel.factorytest.ChamberMode;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Looper;
import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.view.WindowManager;
import android.net.Uri;
import android.util.Log;
import android.os.SystemProperties;

import com.intel.factorytest.R;
import com.intel.factorytest.util.LogUtils;
import com.intel.factorytest.util.Util;
import com.intel.factorytest.util.ShellUtilsPlus;
import com.intel.factorytest.ChamberMode.ChamberModeMainActivity;
import com.intel.factorytest.ChamberMode.ChambermodeBaseActivity;


import static android.content.Context.AUDIO_SERVICE;


public class EarpiecTest extends ChambermodeBaseActivity{
    private final static int EARPIEC_TEST_MSG_UPDATE_UI = 1;
    private final static int EARPIEC_TEST_MSG_TIME_OUT = 2;

    Context mContext;
    private MediaPlayer mMediaPlayer;
    AudioManager audioManager;
    private static int save_volume_music = 30;
    private static boolean mIsComplete = false;
    private int mTimeout = 20000;
    private EarpiecDown mEarpiecDown = null;

    protected Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case EARPIEC_TEST_MSG_UPDATE_UI: {                    
                    removeMessages(EARPIEC_TEST_MSG_UPDATE_UI);
                    updateTitle("");
                    //ScreenOff();
                    break;
                }
                case EARPIEC_TEST_MSG_TIME_OUT: {                    
                    removeMessages(EARPIEC_TEST_MSG_TIME_OUT);
                    if(!mIsComplete) {
                        stopEarpiec();
                    }
                    Util.isEarpiecTesting = false;                    
                    SystemProperties.set("persist.sys.chamber_run","true");
                    if(mIsComplete) {
                        finish();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };
    
    @Override
    public void onCreate(Bundle b) {
        super.onCreate(b);
        LogUtils.loge("onCreate");
        mContext = getApplicationContext();
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
        audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
        //audioManager.setMode(AudioManager.MODE_NORMAL);
        save_volume_music = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);        
        //audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 100, 20);
    }

    @Override
    public void onResume() {
        LogUtils.loge("onResume");        
        SystemProperties.set("persist.sys.chamber_run","false");
        super.onResume();
    }
    
    @Override
    protected void startTest(){
        LogUtils.logi("startEarpieceTest");        
        Util.isEarpiecTesting = true;
        updateTitle("Earpiece Audio");
        sendDelayedMsg(EARPIEC_TEST_MSG_UPDATE_UI,5000,null,null,mHandler);
        startEarpiec(mContext);
        if (mTimeout > 0){
            LogUtils.logi("startEarpieceTest play 20s");
            new countDownThread().start();
        }
    }
    
    @Override
    protected void stopTest(){
        LogUtils.logi("stopSpeakerTest");
        stopEarpiec();
    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtils.loge( "onPause() ");
        if ( mEarpiecDown != null ) mEarpiecDown.cancel();
    }

    @Override
    public void onStop() {
        super.onPause();
        LogUtils.loge( "onStop() ");        
        stopEarpiec();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.loge( "onDestroy() ");
       if (mMediaPlayer!= null) {
            mMediaPlayer = null;
        }
        if (mEarpiecDown != null) {
            mEarpiecDown = null;
        }
    }
    
    @Override
    public void finish() {
        Intent i = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString(ChamberModeMainActivity.EARPIEC_RESULT, "earpiec_test_finish");        
        i.putExtras(bundle);
        setResult(ChamberModeMainActivity.START_EARPIEC_TEST_RESULT_CODE,i);
        super.finish();
    }

    private class countDownThread extends Thread{
        public countDownThread(){}

        @Override
        public void run() {
            LogUtils.logi("countDownThread  run()");
            // TODO Auto-generated method stub
            Looper.prepare();
            mEarpiecDown = new EarpiecDown();
            mEarpiecDown.start();
            Looper.loop();
        }
    }
    
    private class EarpiecDown extends CountDownTimer{

        public EarpiecDown() {
            super(mTimeout,mTimeout);
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            LogUtils.logi("Time Out:");
            mHandler.sendEmptyMessage(EARPIEC_TEST_MSG_TIME_OUT);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
        }
    }

    public void startEarpiec(Context context){
        LogUtils.logi("startEarpiec start");
        Uri uri = Uri.parse("android.resource://com.intel.factorytest/" + R.raw.test_1khz);
        LogUtils.logi("startEarpiec uri = " + uri);
        //mMediaPlayer = MediaPlayer.create(context, uri);
        //mMediaPlayer = MediaPlayer.create(this, R.raw.r_ch); //play from resource
        try {
            LogUtils.logi( "startEarpiec mMediaPlayer.isPlaying() = " + mMediaPlayer.isPlaying());
            mMediaPlayer.setDataSource(context, uri);
            mMediaPlayer.setLooping(true); 
            if (mMediaPlayer.isPlaying()) {                
                mMediaPlayer.stop();
            }
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            mMediaPlayer.setVolume(1f, 1f);
            mIsComplete = false;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stopEarpiec(){
        try {
            if(mMediaPlayer != null){
                LogUtils.logi( "stopEarpiec mMediaPlayer.isPlaying() = " + mMediaPlayer.isPlaying());
                if(mMediaPlayer.isPlaying())
                {
                    mMediaPlayer.stop();
                    mMediaPlayer.prepare();
                }
                mMediaPlayer.release();
                //recoverMode();
                mMediaPlayer = null;
                mIsComplete = true;
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void recoverMode() {
        LogUtils.logi( "recoverMode");
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                save_volume_music, AudioManager.FLAG_PLAY_SOUND);
    }

    public Uri getDefaultRingtoneUri(Context context,int type) {
        LogUtils.logi("getDefaultRingtoneUri");
        return RingtoneManager.getActualDefaultRingtoneUri(context, type);
    }
}
